package com.tg.paw.ums.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tg.paw.common.annotation.SysLog;
import com.tg.paw.common.constant.AllEnum;
import com.tg.paw.common.generator.IdGeneratorUtil;
import com.tg.paw.common.model.PageResult;
import com.tg.paw.common.model.TreeNode;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.common.util.NameUtil;
import com.tg.paw.ums.dto.OperatePermissionDto;
import com.tg.paw.ums.entity.Permission;
import com.tg.paw.ums.service.IPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户权限表 前端控制器
 * </p>
 *
 * @author Rubble
 * @since 2020-06-14
 */
@RestController
@Slf4j
@Api(tags = "后台用户权限表管理", value = "PermissionController")
@RequestMapping("/permission")
public class ApiPermissionController {
    @Autowired
    private IPermissionService permissionService;


    @SysLog(MODULE = "ums", REMARK = "查询权限树")
    @ApiOperation("查询权限树")
    @GetMapping(value = "/listTree")
    public CommonResult getPermission(Permission entity) {
        try {
            // 条件查询权限
            List<Permission> queryPermissions = permissionService.list(new QueryWrapper<>(entity));
            // 全部权限
            List<Permission> permissions = permissionService.list();
            List<Permission> treeData = null;
            // 全部 结果 组织成树
            if(permissions.size()==queryPermissions.size()){
                treeData = getPermissionChildren(permissions,0L);
            }else {
                treeData = queryPermissions;
            }
            PageResult<Permission> pageResult = new PageResult<>();
            pageResult.setPageSize(permissions.size());
            pageResult.setCurrent(1);
            pageResult.setTotalPage(1);
            pageResult.setTotal(permissions.size());
            pageResult.setData(treeData);
            return CommonResult.success(pageResult);
        } catch (Exception e) {
            log.error("查询权限树：{}", e.getMessage(), e);
        }
        return CommonResult.failed();
    }

    @SysLog(MODULE = "ums", REMARK = "选择权限树")
    @ApiOperation("选择权限树")
    @GetMapping(value = "/getSelectTree")
    public CommonResult getSelectTree() {
        try {
            // 全部权限
            List<Permission> permissions = permissionService.list();
            List<TreeNode> treeNodes = buildTreeNodeChildren(permissions,"0");

            return CommonResult.success(treeNodes);
        } catch (Exception e) {
            log.error("选择权限树：{}", e.getMessage(), e);
        }
        return CommonResult.failed();
    }


    @SysLog(MODULE = "ums", REMARK = "更新按钮权限")
    @ApiOperation("更新按钮权限")
    @PostMapping(value = "/operatePermission")
    public CommonResult updateOperatePermission(@Valid @RequestBody OperatePermissionDto operatePermissionDto, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return CommonResult.validateFailed(bindingResult);
        }
        Permission permission = permissionService.getById(operatePermissionDto.getPermissionId());
        if(permission.getPermissionType()!=1){
            return CommonResult.failed("设置操作权限必须为菜单类型.");
        }
        Permission condition = new Permission();
        condition.setParentId(operatePermissionDto.getPermissionId());
        List<Permission> list = permissionService.list(new QueryWrapper<>(condition));
        List<String> operators = operatePermissionDto.getOperators()!=null ? operatePermissionDto.getOperators(): new ArrayList<>();
        List<String> existsList = new ArrayList<>();
        for (Permission item :
                list) {
//            if(operators.contains(item.getPermissionValue())){
//                existsList.add(item.getPermissionValue());
//            }else{
//                permissionService.removeById(item.getPermissionId());
//            }
        }
        Map<String,String> map = new HashMap<>();
        map.put("query", "查询");
        map.put("add", "新增");
        map.put("edit", "修改");
        map.put("delete", "删除");
        map.put("detail", "详情");
        map.put("import", "导入");
        map.put("export", "导出");

        for (String item :
                operators) {
            if (existsList.contains(item)){
                continue;
            }
            Permission record = new Permission();
            record.setParentId(operatePermissionDto.getPermissionId());
//            record.setPermissionValue(item);
            String name = map.get(item)!=null?map.get(item):item;
            record.setPermissionName(name);
            permissionService.save(record);
        }

        return CommonResult.success();
    }

    private List<Permission> getPermissionChildren(List<Permission> permissions,long parentId){
        List<Permission> children = permissions.stream().filter(item -> item.getParentId() == parentId).collect(Collectors.toList());
        for (Permission item :
                children) {
            List<Permission> list = getPermissionChildren(permissions, item.getPermissionId());
            if(CollectionUtil.isNotEmpty(list)){
//                item.setChildren(list);
            }
        }

        return children;
    }

    private List<TreeNode> buildTreeNodeChildren(List<Permission> permissions,String parentId){
        List<Permission> permissionList = permissions.stream().filter(item -> String.valueOf(item.getParentId()).equals(parentId)).collect(Collectors.toList());
        List<TreeNode> children = convert2TreeNode(permissionList);

        for (TreeNode item :
                children) {
            List<TreeNode> subChildren = buildTreeNodeChildren(permissions, item.getKey());
            if(CollectionUtil.isNotEmpty(subChildren)){
                item.setChildren(subChildren);
            }
        }
        return children;
    }

    private TreeNode convert2TreeNode(Permission permission){
        TreeNode treeNode = new TreeNode();
        treeNode.setTitle(permission.getPermissionName());
        treeNode.setKey(permission.getPermissionId().toString());
        treeNode.setValue(permission.getPermissionId().toString());
        return treeNode;
    }

    private List<TreeNode> convert2TreeNode(List<Permission> permissions){
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Permission permission:
                permissions) {
            treeNodes.add(convert2TreeNode(permission));
        }

        return treeNodes;
    }


}
